import util from "../../../utils/util.js";
import api from "../../../common/api.js";
import {
  insertNewHouseLog
} from "../../../common/log.js";
import {
  xstShare
} from "../../../common/subscribe.js";
import p from "../../../utils/platform.js";
import constant from "../../../common/constant.js";
const config = require('../../../utils/config.js');
var userId;
var app = getApp();

Page({
  /**
   * 页面的初始数据
   */
  data: {
    addToMy: false, // 是否已添加到我的房源
    currentTabState: 0,
    tabList: config.tabList,
    reason: '', //下架理由
    time: '', //下架时间
    widthVi: app.globalData.windowHeight,
    isUpdate: false, //有没有修改房源详情
    friendsShowDialog: false,
    pyqmodal: false, //点击朋友圈分享后的弹窗
    isPageShow: true, //页面等数据请求完成再显示
    currentSwiper: 0, //轮播图当前位置
    tagName: '', //轮播图标签
    showDialog: false,
    listTabShowDialog: false,
    contactShowDialog: false,
    shareShowDialog: false,
    copyShowDialog: false,
    houdelid: '', //房源ID
    detailContent: '', //房源详情
    markers: [],
    from: true,
    loadSeccess: true,
    houseTypes: "",
    copyText: '',
    counts: 0,
    shorturlL: '',
    enterStyle: 'share', //进来的方式为分享或添加
    modifyPrice: false, //修改的弹出框
    price: 61100,
    changePrice: '',
    currentTab: '0',
    source: "new",
    city: null,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    app.globalData.loginPromise.then(({
      sessionUser
    }) => {
      userId = sessionUser.id

      this.getHouseInfo();
    })

    /*
     @from :true: 列表
           false:成功
     */
    wx.setStorageSync("houDelId", options.houdelid);
    wx.gio('setPage', {
      [constant.ROOM_TYPE_PVAR]: constant.XIN_FANG
    })

    if (options.city) {
      this.data.city = options.city
    }
    if (options.isMay == "false") {
      console.log("列表进来");
      this.setData({
        houdelid: options.houdelid,
        // houdelid: '821167024ea74d5882193c396698e253',
        enterStyle: "add",
        source: "old"
      })
    } else {
      console.log("成功进来");
      this.setData({
        houdelid: options.houdelid,
        // houdelid: '821167024ea74d5882193c396698e253',
        enterStyle: "share",
        source: "new"
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function (options) {
    app.globalData.loginPromise.then(({
      sessionUser
    }) => {
      userId = sessionUser.id

      var houdelid = wx.getStorageSync("houdelid");
      if (houdelid == '1') {
        wx.removeStorageSync('houdelid')
        this.setData({
          shareShowDialog: !this.data.shareShowDialog
        });

      }

      if (this.data.isUpdate) {
        this.getHouseInfo();
      }

      this.setData({
        currentTabState: app.globalData.mapTabStatusIndex
      })

    })

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    app.globalData.mapTabStatusIndex = 0

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  // 取消修改新房价格
  modifyPricecancel() {
    this.setData({
      modifyPrice: false
    })
  },

  // 实时获取修改新房价格的value
  bindKeyInput(e) {
    // console.log(e);
    let that = this;
    var value = e.detail.value;
    that.setData({
      changePrice: value
    })
  },

  // 跳转到新房相册
  goAlbum() {
    let hdResblockId = this.data.detailContent.hd_new_house_resblock_id ? this.data.detailContent.hd_new_house_resblock_id : this.data.detailContent.id;
    wx.navigateTo({
      url: '../newAlbum/newAlbum?hdResblockId=' + hdResblockId + '&source=' + this.data.source,
    })
  },

  // 确定修改新房价格
  modifyPriceconfirm() {
    let that = this;
    let data = {
      houseResblockId: that.data.houdelid,
      averagePrice: that.data.changePrice
    }
    api.updateNewHouseAveragePrice(data, (res) => {
      that.setData({
        modifyPrice: false,
      })
      that.getHouseInfo();
    })
  
  },

  // 添加新房
  addNewhouse() {
    api.addNewHouse({
      hdId: this.data.houdelid
    }, res => {
      if (res.data.isSuccess) {
        this.setData({
          addToMy: true
        })
        wx.showToast({
          title: '已成功添加',
        })
      }

      insertNewHouseLog({
        logType: "4",
        cityName: this.data.city,
        floorId: this.data.houdelid,
        createResult: res.data.isSuccess ? 0 : 1,
        delId: res.data.isSuccess ? res.data.content : null
      })
    })
  },

  swiperChange(e) {
    const that = this,
      currentSwiper = e.detail.current;
    const tagName = that.data.detailContent.houImageVO[currentSwiper].tagName;
    this.setData({
      currentSwiper: currentSwiper,
      tagName: tagName
    })
  },

  callPhone(e) {
    var num = e.currentTarget.dataset.phonenum;
    wx.makePhoneCall({
      phoneNumber: num,
    })
  },

  toggleListTabDialog() {
    this.setData({
      listTabShowDialog: !this.data.listTabShowDialog
    });
  },

  //跳转访客
  goVisitors() {
    wx.navigateTo({
      url: '/pages/visitors/visitors?id=' + this.data.detailContent.houDelVO.id,
    })
  },

  toggleContacTabDialog() {
    this.setData({
      contactShowDialog: !this.data.contactShowDialog
    });
  },

  toggleShareTabDialog() {
    this.setData({
      shareShowDialog: !this.data.shareShowDialog,
      friendsShowDialog: false,
      pyqmodal: false
    });

    if (this.data.shareShowDialog) {
      xstShare()
    }
  },

  toggleDialog(e) {
    var current = e.currentTarget.dataset.current;
    if (!current) {
      current = this.data.current;
      this.setData({
        showDialog: false
      });
    } else if (current == this.data.current) {
      this.setData({
        showDialog: !this.data.showDialog
      });
    } else {
      this.setData({
        showDialog: true
      });
    }
    if (current) {
      this.setData({
        current: current
      });
    } else {
      this.setData({
        current: this.data.current
      });
    }
  },

  //房源列表图片错误
  imageError(e) {
    const that = this;
    var errorIndex = e.target.dataset.index;
    var avatar = that.data.detailContent.jjrVO.avatar;
    that.data.detailContent.jjrVO.avatar = "/images/default_head.png";

    that.setData({
      houseList: houseListArr,
    })
  },

  //跳转角色人
  goRole() {
    wx.navigateTo({
      url: '/pages/house/RentalHouseDetail/role/role',
    })
  },

  //跳转委托
  goEntrust() {
    wx.navigateTo({
      url: '/pages/house/RentalHouseDetail/entrust/entrust',
    })
  },

  //跳转钥匙
  goKey() {
    wx.navigateTo({
      url: '/pages/house/RentalHouseDetail/key/key',
    })
  },

  //跳转小区详情
  goHousingEstateDetail() {
    wx.navigateTo({
      url: '/pages/house/housingEstateDetail/housingEstateDetail',
    })
  },

  //无效房源
  goFailRoom() {
    const id = this.data.detailContent.houDelVO.id
    var that = this;
    wx.showModal({
      title: '提示',
      content: '您确定将该房源标记为无效房源吗',
      confirmText: "确定",
      cancelText: "取消",
      success(res) {
        if (res.confirm) {
          wx.showLoading({
            title: '加载中',
          })
          api.houseFail(id, {}, (res) => {
            wx.hideToast();
            // wx.reLaunch({
            //   url: '/pages/index/index'
            // })
            // TODO: 返回列表并且刷新
            var pages = getCurrentPages();
            var currPage = pages[pages.length - 1]; //当前页面
            var prevPage = pages[pages.length - 2]; //上一个页面
            const option = {
              type: that.data.houseTypes
            }
            wx.navigateBack();
            prevPage.backRefash && prevPage.backRefash(option);
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },

  //跳转修改房源
  goRentalHouseModify() {

    wx.navigateTo({
      url: '/pages/addHouse/infoEntryHouse/infoEntryHouse?houDelId=' + this.data.detailContent.houDelVO.id,
    })

  },

  //跳转全部带看
  goLookerList() {
    wx.navigateTo({
      url: '/pages/house/RentalHouseDetail/lookerLsit/lookerLsit',
    })
  },

  // 时间戳转换成日期
  timestampToTime(timestamp) {
    var date = new Date(timestamp); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
    var Y = date.getFullYear() + '/';
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '/';
    var D = date.getDate() + ' ';
    var h = date.getHours() + ':';
    var m = date.getMinutes() + ':';
    var s = date.getSeconds();
    return Y + M + D;
  },

  //获取房源详情
  getHouseInfo() {
    const that = this,
      bannerList = [];
    api.getnewHouseInfo({
      newDelId: that.data.houdelid,
      source: that.data.source
    }, (res) => {
      console.log("房源详情data===", res.data.content)
      const content = res.data.content;
      bannerList.push(content.first_picture_url)
      const reasonOptions = {
        7: '楼盘售罄',
        8: '停止合作',
        6: '其他原因停止交易'
      }
      let reason = content.reason ? reasonOptions[content.reason.trim()] || '' : ''
      that.setData({
        markers: [{
          id: 0,
          latitude: content.lat,
          longitude: content.lng,
          title: content.resblockName,
        }],
        bannerList: bannerList,
        detailContent: content,
        isPageShow: true,
        loadSeccess: true,
        time: content.changeTime ? that.timestampToTime(content.changeTime) : '',
        reason: reason,
      })
      // that.getCount();
      that.getNewhousetype();
    })
  },

  // 获取新房户型图
  // getNewhousetype() {
  //   console.log(666, this.data.detailContent.hd_new_house_resblock_id)
  //   api.getNewhousetype({
  //     houseResblockId: this.data.detailContent.hd_new_house_resblock_id
  //   },res=>{
  //     var houseTypelist = Object.keys(res.data.content)
  //     // console.log(houseTypelist)
  //     this.setData({
  //       newHousetype: res.data.content,
  //       houseTypelist: houseTypelist,
  //     })
  //   })
  // },

  //粉丝列表
  getFuns() {
    var that = this;
    api.getFuns({
      delId: that.data.houdelid
    }, (res) => {
      that.setData({
        funsList: res.data.content
      })

    })
  },

  //预览轮播图
  previewBannerImage: function (e) {
    var newHousetype = this.data.newHousetype;
    var url = [];
    for (var index in newHousetype) {
      url = url.concat(newHousetype[index].fileId);
    }
    wx.previewImage({
      current: e.currentTarget.dataset.currentimg,
      urls: url,
    })
  },

  //预览名片
  previewImage: function (e) {
    var image = e.currentTarget.dataset.image;
    var urls = new Array();
    urls.push(image);

    wx.previewImage({
      urls: urls,
    })
  },

  //跳转直接分享----到树懒找房小程序---带各种ID 和房源详情的相关数据
  _newHouseShare(goZhaofang) {
    var allId = {};
    var loginUserInfo = getApp().globalData.loginUserInfo
    const sessionUser = loginUserInfo.data.content.sessionUser
    allId.agentId = sessionUser.id;
    allId.storeId = sessionUser.extProps.storeId;
    allId.mkId = "EMP";
    allId.houDelId = this.data.detailContent.id;
    allId.newHouse = 'new';
    allId.realName = sessionUser.realName
    allId.mobile = sessionUser.mobile
    allId.wxHeadImg = sessionUser.avatar || sessionUser.extProps.wxHeadImg

    var extraData = {
      roomDetail: this.data.detailContent,
      allId: allId,
      type: 'coupon'
    }
    extraData.roomDetail.isNewHouse = true
    extraData.allId.isTranspond = true;

    if (goZhaofang) {
      app.globalData.houseShareBannerInfo = JSON.parse(JSON.stringify(extraData))
      console.log("app.globalData.houseShareBannerInfo==", app.globalData.houseShareBannerInfo);
      p.navigateTo({
        url: "/pages/house/RentalHouseDetail/oldHouseShare/oldHouseShare"
      })

      wx.gio('track', constant.SHARE_SUCCESS, {
        [constant.ROOMTYPE_VAR]: constant.XIN_FANG,
        [constant.SHARETYPE_VAR]: constant.HB_SHARE,
      })

    } else {
      wx.navigateToMiniProgram({
        appId: 'wx5adc5dd9870f6a26', //树懒找房极速版appid
        // path: 'pages/houseShare/newHouseShare/newHouseShare',
        path: 'pages/houseShare/newRentalHouseDetail/newRentalHouseDetail?jingjiId=' + JSON.stringify(extraData),
        extraData: extraData,
        envVersion: util.envVersion,
        success: (res) => {
          // 打开成功 
          wx.gio('track', constant.SHARE_SUCCESS, {
            [constant.ROOMTYPE_VAR]: constant.XIN_FANG,
            [constant.SHARETYPE_VAR]: constant.ZJ_SHARE,
          })
        },
        fail(res) {
          //
        }
      })
    }
  },

  handleDirectShare() {
    api.shareHouseLog({
      sourceApp: '0',
      shareType: '1',
      delId: this.data.detailContent.id
    })
    wx.gio('track', constant.HANDLE_SHARE, {
      [constant.ROOMTYPE_VAR]: constant.XIN_FANG,
      [constant.SHARETYPE_VAR]: constant.ZJ_SHARE,
      [constant.SHARESOURCE_VAR]: constant.DETAILS_SHARE
    })
    this._newHouseShare()
  },

  handleShareBanner() {
    api.shareHouseLog({
      sourceApp: '0',
      shareType: '3',
      delId: this.data.detailContent.id
    })
    wx.gio('track', constant.HANDLE_SHARE, {
      [constant.ROOMTYPE_VAR]: constant.XIN_FANG,
      [constant.SHARETYPE_VAR]: constant.HB_SHARE,
      [constant.SHARESOURCE_VAR]: constant.DETAILS_SHARE
    })
    this._newHouseShare(true)
  },

  friendsShareTabDialog() {
    let that = this;
    that.setData({
      friendsShowDialog: false,
      pyqmodal: false
    })
  },

  //分享到朋友圈，复制关键信息及链接
  goSharepyq() {
    api.shareHouseLog({
      sourceApp: '0',
      shareType: '2',
      delId: this.data.detailContent.id
    })
    wx.gio('track', constant.HANDLE_SHARE, {
      [constant.ROOMTYPE_VAR]: constant.XIN_FANG,
      [constant.SHARETYPE_VAR]: constant.PYQ_SHARE,
      [constant.SHARESOURCE_VAR]: constant.DETAILS_SHARE
    })

    let that = this;
    this.setData({
      shareShowDialog: true,
      friendsShowDialog: true,
      // pyqmodal: true
    })
    var loginUserInfo = getApp().globalData.loginUserInfo
    api.oldHouseInfo({
      agentid: loginUserInfo.data.content.sessionUser.id,
      openid: wx.getStorageSync('aldstat_op')
    })
  },

  toggleCopyShowDialog() {
    this.setData({
      copyShowDialog: false,
    })
  },

  // 修改新房价格
  updateNewHouseAveragePrice() {
    this.setData({
      modifyPrice: true,
    })
  },

  //复制关键信息及链接
  goCopy() {
    let that = this;
    that.setData({
      friendsShowDialog: false,
      shareShowDialog: false
    })
    let detailContent = this.data.detailContent;
    let userid = getApp().globalData.loginUserInfo.data.content.sessionUser.id;
    var loginUserInfo = getApp().globalData.loginUserInfo
    console.log(110, `${util.shareUrl}/noauth/hou/houseNewDetail?houDelId=${detailContent.id}&userId=${userid}`)
    let message = {
      "touser": wx.getStorageSync('aldstat_op'),
      "msgtype": "link",
      "link": {
        "title": that.data.detailContent.title + '分享链接',
        "description": "点击可以分享至朋友圈",
        "url": `${util.shareUrl}/noauth/hou/houseNewDetail?houDelId=${detailContent.id}&userId=${userid}`,
        "thumb_url": `${detailContent.first_picture_url}`
      }
    };
    api.setHouseInfo({
      agentid: loginUserInfo.data.content.sessionUser.id,
      openid: wx.getStorageSync('aldstat_op'),
      message: JSON.stringify(message)
    }, (res) => {
      console.log('成功发送客服消息', res)

      wx.gio('track', constant.SHARE_SUCCESS, {
        [constant.ROOMTYPE_VAR]: constant.XIN_FANG,
        [constant.SHARETYPE_VAR]: constant.PYQ_SHARE,
      })
    })
  },


  getCount() {
    let that = this;
    api.getCount({
      houDelId: that.data.houdelid
    }, (res) => {
      that.setData({
        counts: res.data.content
      })
    })
  },

  // 获取新房户型图
  getNewhousetype() {
    api.getNewhousetype({
      houseResblockId: this.data.detailContent.hd_new_house_resblock_id
      // houseResblockId: 
    }, res => {
      var houseTypelist = res.data.content;
      if (houseTypelist.length > 0) {
        api.getNewhouseImg({
          houseResblockId: this.data.detailContent.hd_new_house_resblock_id,
          roomType: res.data.content[0].room_type,
          source: this.data.source,
          "userId": userId,
        }, res => {
          this.setData({
            newHousetype: res.data.content,
            houseTypelist: houseTypelist,
          })
        })
      }
    })
  },

  clickTab: function (e) {
    api.getNewhouseImg({
      houseResblockId: this.data.detailContent.hd_new_house_resblock_id,
      roomType: e.target.dataset.room,
      source: this.data.source,
      "userId": userId,
    }, res => {
      this.setData({
        currentTab: e.target.dataset.cuttent,
        newHousetype: res.data.content
      })
    })
  },

  houseUndercarriage() {
    let delId = this.data.houdelid;
    wx.navigateTo({
      url: `../../house/houseUndercarriage/houseUndercarriage?delId=${delId}&type=new`
    })
  },

  houseReturn() {
    let that = this;
    let id = {
      delId: that.data.houdelid,
      state: "AVAILABLE",
      invalidType: 1,
    }
    api.houseFail('', id, (res) => {
      wx.showToast({
        title: '房源已上架',
      })
      that.getHouseInfo()
    })
  },

  handleNavigation() {
    const lat = this.data.detailContent.lat
    const lng = this.data.detailContent.lng
    wx.openLocation({
      latitude: Number(lat),
      longitude: Number(lng),
      scale: 16
    })
  },

  goMapDetails(e) {
    const currentTitle = e.currentTarget.dataset.title
    const currentTabState = e.currentTarget.dataset.index
    const lat = this.data.detailContent.lat
    const lng = this.data.detailContent.lng
    this.setData({
      currentTabState
    })
    wx.navigateTo({
      url: `/pages/house/RentalHouseDetail/mapDetails/mapDetails?latitude=${lat}&longitude=${lng}&currentTitle=${currentTitle}&currentTabState=${currentTabState}`
    })
  },

  putHouse() {
    let delId = this.data.houdelid;
    wx.showModal({
      title: '提示',
      content: '是否重新上架房源?',
      success: (res) => {
        if (res.confirm) {
          api.downNewHouseById({
            delId: delId,
            state: "AVAILABLE",
            invalidType: 1,
            reasonCode: '',
          }, (result) => {
            if (result && result.data && result.data.isSuccess) {
              wx.redirectTo({
                url: `/pages/newBuildinghouse/newRentalHouseDetail/newRentalHouseDetail?houdelid=${delId}&isMay=true`,
              });
            } else {
              wx.showToast({
                icon: 'none',
                title: '上架失败，请稍后再试',
              })
            }
          });
        }
      }
    })
  },
  
})